import React,{useState,useEffect,useRef} from 'react';
import { Table, Button, Modal, Switch, } from 'antd'
import axios from '_axios@0.27.2@axios';
import { EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import FormItem from '../../../components/user-manage/FormItem'
const UserList = () => {
  const [dataSource, setdataSource] = useState([])
  const [regionList, setregionList] = useState([])
  const [roleList, setroleList] = useState([])
  const [isEditModalVisible, setisEditModalVisible] = useState(false)
  const [isUpdataDisable, setisUpdataDisable] = useState(false)
  const [esitCurrentId,setesitCurrentId] = useState(null)
  const editAddForm = useRef(null)
  const addForm = useRef(null)
  const [isModalVisible, setisModalVisible] = useState(false)
  const {roleId,region,username} = JSON.parse(localStorage.getItem('token'))

  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      filters: [
        ...regionList.map(item => ({ text: item.title, value: item.value })),
        {text:'全球',value:'全球'}
      ],
      onFilter: (value, item) => {
        if (value==="全球") {
          return item.region === ''
        }
        return item.region === value
      },
      render: (region) => {
       return <b>{ region?region: '全球' }</b>
      }
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role) => {
        return <div>{ role.roleName}</div>
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '状态',
      dataIndex: 'roleState',
      render: (roleState,item) => {
       return <Switch checked={roleState} onChange={()=>switchMethod(item)} disabled={item.default}></Switch>
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Button
            danger
            shape="circle"
            disabled={item.default}
            onClick={() => confirmMethod(item)}
            icon={<DeleteOutlined />}
          />
          <Button
            onClick={()=>handleUpdate(item)}
            type="primary"
            disabled={item.default}
            shape="circle"
            icon={<EditOutlined />}
          />
       </div>
      }
    },
  ];
  // 修改
  const handleUpdate = (item) => {
    setisEditModalVisible(true)
    setesitCurrentId(item.id)
      if (item.role.roleType == 1) {
        setisUpdataDisable(true)
      } else{
        setisUpdataDisable(false)
      }
      setTimeout(() => {
        editAddForm.current.setFieldsValue(item) // 赋值
      },100)
  }
  // 修改
  const editHandleOk = () => {
    editAddForm.current.validateFields().then(val => {
      setisEditModalVisible(false)
      axios.patch(`/users/${esitCurrentId}`, val).then(data => {
        getUserData()
        addForm.current.resetFields()
      })
    })
  }
  // 开关
  const switchMethod = (item) => {
    item.roleState = !item.roleState
    setdataSource([...dataSource])
      axios.patch(`/users/${item.id}`, {
        roleState:item.roleState
      })
  }
  // 删除提示
  const confirmMethod = (item) => {
    Modal.confirm({
    title: '删除',
    icon: <ExclamationCircleOutlined />,
    content: '你确认删除吗？',
    okText: '确认',
    cancelText: '取消',
      onOk() {
        deleteMethod(item)
      }
    })
  }
  // 删除
  const deleteMethod = (item) => {
    setdataSource(dataSource.filter(data => data.id !== item.id))
    axios.delete(`/users/${item.id}`)
  }
  // 获取列表数据
  const getUserData = () => {
     axios.get('/users?_expand=role').then(res => {    
       setdataSource(roleId === 1 ? res.data : [
         ...res.data.filter(item => item.username === username),
         ...res.data.filter(item=> item.region===region && item.roleId === 3)
      ])
    })
  }
  // 初始化
  useEffect(() => {
   getUserData()
  }, [])
  // 获取区域数据
  useEffect(() => {
    axios.get('/regions').then(res => {    
      setregionList(res.data)
    })
  }, [])
   // 获取角色数据
  useEffect(() => {
    axios.get('/roles').then(res => {    
      setroleList(res.data)
    })
  }, [])
  // 对话框确定
  const handleOk = () => {
    addForm.current.validateFields().then(res => {
      setisModalVisible(false)
      axios.post(`/users`, {
        ...res,
        "roleState": true,
        "default": false
      }).then(data => {
        getUserData()
        addForm.current.resetFields()
      })
     
    }).catch(err => {
      console.log('失败===',err)
    })
  }
  // 对话框取消
  const esitHandleCancel = () => {
    setTimeout(() => {
        setisEditModalVisible(false)
      },100)
      setisUpdataDisable(!isUpdataDisable)
  }
  return (
    <div>
      <Button type="primary" onClick={()=>setisModalVisible(true)}>新增用户</Button>
      <Table dataSource={dataSource} columns={columns}
        rowKey={(item)=>item.id}
        pagination={{
          pageSize: 5
        }}
      />;
      
      <Modal title="新增用户" visible={isModalVisible} onOk={handleOk} onCancel={() => {
        setisModalVisible(false)
       }}>
        <FormItem regionList={regionList} roleList={roleList} ref={addForm}></FormItem>
      </Modal>
      <Modal
        title="编辑用户"
        onOk={editHandleOk}
        visible={isEditModalVisible}
        onCancel={() =>esitHandleCancel()}>
        <FormItem isDisableState={true} regionList={regionList} roleList={roleList} ref={editAddForm} isUpdataDisable={isUpdataDisable}></FormItem>
      </Modal>
    </div>
  );
}

export default UserList;

